package com.bodacn.keypoint;


import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import org.json.JSONArray;
import org.json.JSONException;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentMateSend extends Fragment implements View.OnClickListener {
    public static String TAG= FragmentMateSend.class.getName();
    public static final int msgFocusBarcode = 1001;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_DetailOver =9002;
    public static final int MSG_ERRMSG =9008;
    LinearLayout mainLinerLayout;
    ReentrantLock reentrantLock = new ReentrantLock();
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    SQLiteDatabase tmpdb;
    //全局变量
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curFactory="",curDepart,CPUID;
    boolean curActive=false;
    EditText edt_barcode;
    JSONArray detailJson,chartJSON;
    String PrBarcode="";
    CheckBox chkIncludeSend;
    EditText edt_WorkDate;
    Button btn_UpDate,btn_DownDate;
    ListView listDetail;
    Button btn_Refresh;

    private ProgressDialog waitDialog = null;

    boolean AllowScan=true;

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public FragmentMateSend() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        //全局App;
        try {
            detailJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(TAG+"onCreate-------------------------------------1");
        //创建适配器
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerMateSend(new MainActivity.OnTransParamsListenerMateSend() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        System.out.println(mParams);
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(this.getClass().getName(),"LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir= mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            curFactory=mParams.get("Factory").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(this.getClass().getName(),"LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if ((paramComm=="RefreshDetail")&&curActive){
                            refreshDetail( edt_WorkDate.getText().toString(),chkIncludeSend.isChecked()?"1":"0");
                        }
                        if ((paramComm=="Barcode")&&curActive){
                            String barcode=mParams.get("Barcode").toString();

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        System.out.println(TAG+"onCreate-------------------------------------2");

    }

    //自动刷新数据
    private void refreshDetail(String paramDate, String paramIncludeOver) {
        System.out.println(TAG+":准备刷新明细图表");
        String sqlcmd="Exec KeyPoint_MateSendGetList @OperType='Detail',@DepartNo='" + curDepartNo
                +"',@NeedDate='" + paramDate+"',@IncludeOver='" + paramIncludeOver+"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlcmd);
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_matesend, container, false);

        InitView(root);
        //文本框
        edt_WorkDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(v.getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,"完成",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edt_WorkDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle("选择查询起始日期");
                mDialog.show();

            }
        });
        edt_WorkDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("edit_startDate","onFocusChange");
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        String dateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
        edt_WorkDate.setText(dateStr);
        System.out.println(this.getClass().getName()+"_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        waitDialog= new ProgressDialog(getContext());
        waitDialog.setTitle(getString(R.string.SystemHint));
        chkIncludeSend=view.findViewById(R.id.chkIncludeSend);
        edt_WorkDate=view.findViewById(R.id.edt_WorkDate);
        btn_UpDate=view.findViewById(R.id.btn_UpDate);
        btn_UpDate.setOnClickListener(this);
        btn_DownDate=view.findViewById(R.id.btn_DownDate);
        btn_DownDate.setOnClickListener(this);
        listDetail=view.findViewById(R.id.listDetail);
        btn_Refresh=view.findViewById(R.id.btn_Refresh);
        btn_Refresh.setOnClickListener(this);
    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+ R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }

    @Override
    public void onResume() {
        super.onResume();
       hideBottomUIMenu();
    }





    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        Bundle paramBundle = new Bundle();
        switch (v.getId()){
            case R.id.btn_UpDate:
                edt_WorkDate.setText(StringToDate(edt_WorkDate.getText().toString(),-1));
                refreshDetail( edt_WorkDate.getText().toString(),chkIncludeSend.isChecked()?"1":"0");
                break;
            case R.id.btn_DownDate:
                edt_WorkDate.setText(StringToDate(edt_WorkDate.getText().toString(),1));
                refreshDetail( edt_WorkDate.getText().toString(),chkIncludeSend.isChecked()?"1":"0");
                break;
            case R.id.btn_Refresh:
                refreshDetail( edt_WorkDate.getText().toString(),chkIncludeSend.isChecked()?"1":"0");
                break;
            default:
                break;
        }
    }

    //字符串加减天数
    private String StringToDate(String time,int AddDays) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date= null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        System.out.println(date);
        c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, AddDays);// 今天+1天
        Date tmpDate = c.getTime();
        System.out.println(tmpDate);
        String s = format.format(tmpDate);
        return s;
    }

    //dp 转换成px
    public int dp2px(float dp)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("requestCode:"+requestCode+" resultCode:"+resultCode);
        //选合约返回
        if ((requestCode==1000)&&(resultCode==1001)){

        }
        hideBottomUIMenu();
    }



    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //从字符串转颜色
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor=Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()>=7)){
            PenColor=Color.parseColor(StrPenColor);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                if (waitDialog.isShowing()==true) waitDialog.cancel();
                String tmpValue;
                //任意消息来均置焦点
                int msgId = msg.what;
                System.out.println("收到的消息是："+msg.what);
                try {
                    switch (msgId) {

                        case MSG_ERRMSG:
                            Bundle bundle1=msg.getData();
                            String mesg=bundle1.getString("MSG","");
                            curToast.setText(mesg);
                            curToast.show();
                        case MSG_DetailOver:
                            //显示明细数据
                            if (detailJson!=null) {
                                DetailListAdapter detailListAdapter = new DetailListAdapter(getContext());
                                listDetail.setAdapter(detailListAdapter);
                            }
                            break;

                        default:
                            break;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    };


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try{
                    reentrantLock.lock();
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        System.out.println(jsonArray);
                        String OPERTYPE="";
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true) OPERTYPE=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (jsonArray.optJSONObject(0).has("OperType")==true) OPERTYPE=jsonArray.optJSONObject(0).getString("OperType");

                        if (OPERTYPE.toUpperCase().equals("DETAIL")) {
                            detailJson=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_DetailOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                    }else{
                        //显示预排单;
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("MSG","未返回任何数据!");
                        msg.setData(bundle);
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //显示预排单;
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                    reentrantLock.unlock();
                }finally {
                    reentrantLock.unlock();
                }
                //允许扫描
                AllowScan=true;

            }

        };
        new Thread(run).start();
    }


    //打开数据库
    public void OpenCreateDB(){
        if (tmpdb==null) {
            MainActivity activity = (MainActivity) getActivity();
            tmpdb = activity.mainDB;
        }
    }




    //自定义适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.fragment_matesend_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            //view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            int backcolor = getResources().getColor(R.color.content);
            if (position%2==0) view.setBackgroundColor(backcolor);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (detailJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = detailJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if (detailJson.optJSONObject(position).has("Factory") == true) {
                    ((TextView)view.findViewById(R.id.item_Factory)).setText(detailJson.optJSONObject(position).getString("Factory"));
                    ((TextView)view.findViewById(R.id.item_Factory)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("Depart") == true) {
                    ((TextView)view.findViewById(R.id.item_Depart)).setText(detailJson.optJSONObject(position).getString("Depart"));
                    ((TextView)view.findViewById(R.id.item_Depart)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("OrderNo") == true) {
                    ((TextView)view.findViewById(R.id.item_OrderNo)).setText(detailJson.optJSONObject(position).getString("OrderNo"));
                    ((TextView)view.findViewById(R.id.item_OrderNo)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("StyleNo") == true) {
                    ((TextView)view.findViewById(R.id.item_StyleNo)).setText(detailJson.optJSONObject(position).getString("StyleNo"));
                    ((TextView)view.findViewById(R.id.item_StyleNo)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("Factory") == true) {
                    ((TextView)view.findViewById(R.id.item_StyleSort)).setText(detailJson.optJSONObject(position).getString("StyleSort"));
                    ((TextView)view.findViewById(R.id.item_StyleSort)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("PO") == true) {
                    ((TextView)view.findViewById(R.id.item_PO)).setText(detailJson.optJSONObject(position).getString("PO"));
                    ((TextView)view.findViewById(R.id.item_PO)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("PSXX") == true) {
                    ((TextView)view.findViewById(R.id.item_PSXX)).setText(detailJson.optJSONObject(position).getString("PSXX"));
                    ((TextView)view.findViewById(R.id.item_PSXX)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("ColorNo") == true) {
                    ((TextView)view.findViewById(R.id.item_ColorNo)).setText(detailJson.optJSONObject(position).getString("ColorNo"));
                    ((TextView)view.findViewById(R.id.item_ColorNo)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("Color") == true) {
                    ((TextView)view.findViewById(R.id.item_Color)).setText(detailJson.optJSONObject(position).getString("Color"));
                    ((TextView)view.findViewById(R.id.item_Color)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("DBH") == true) {
                    ((TextView)view.findViewById(R.id.item_DBH)).setText(detailJson.optJSONObject(position).getString("DBH"));
                    ((TextView)view.findViewById(R.id.item_DBH)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("PartName") == true) {
                    ((TextView)view.findViewById(R.id.item_PartName)).setText(detailJson.optJSONObject(position).getString("PartName"));
                    ((TextView)view.findViewById(R.id.item_PartName)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("Size") == true) {
                    ((TextView)view.findViewById(R.id.item_Size)).setText(detailJson.optJSONObject(position).getString("Size"));
                    ((TextView)view.findViewById(R.id.item_Size)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("NeedNum") == true) {
                    ((TextView)view.findViewById(R.id.item_NeedNum)).setText(detailJson.optJSONObject(position).getString("NeedNum"));
                    ((TextView)view.findViewById(R.id.item_NeedNum)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("MateReason") == true) {
                    ((TextView)view.findViewById(R.id.item_MateReason)).setText(detailJson.optJSONObject(position).getString("MateReason"));
                    ((TextView)view.findViewById(R.id.item_MateReason)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("CallTime") == true) {
                    ((TextView)view.findViewById(R.id.item_CallTime)).setText(detailJson.optJSONObject(position).getString("CallTime"));
                    ((TextView)view.findViewById(R.id.item_CallTime)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("SendTime") == true) {
                    ((TextView)view.findViewById(R.id.item_SendTime)).setText(detailJson.optJSONObject(position).getString("SendTime"));
                    ((TextView)view.findViewById(R.id.item_SendTime)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("SewRecTime") == true) {
                    ((TextView)view.findViewById(R.id.item_SewRecTime)).setText(detailJson.optJSONObject(position).getString("SewRecTime"));
                    ((TextView)view.findViewById(R.id.item_SewRecTime)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("MateUser") == true) {
                    ((TextView)view.findViewById(R.id.item_MateUser)).setText(detailJson.optJSONObject(position).getString("MateUser"));
                    ((TextView)view.findViewById(R.id.item_MateUser)).setTextColor(color);
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailListAdapter_position:"+position);
            return view;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        curActive=true;

    }

    @Override
    public void onPause() {
        super.onPause();
        curActive=false;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        curActive=!hidden;
        //读配置文件
        System.out.println("curActive:"+curActive);
    }
}
